import router from './router.constant.js'
import store from 'store/index.js'

router.beforeEach((to, from, next) => {
  if (to.name !== 'Login' && !store.state.acc_id) {
    return next({ name: 'Login' })
  }
  // 通过matched 的 commonComp 属性获取当前页面的公共组件,优先取子路由的公共组件
  const matchedRoute = to.matched.reverse().find(i => i.meta.commonComp)
  store.commit('SetCurrentPageCommonComp', matchedRoute ? matchedRoute.meta.commonComp : '')

  // 即将成功进入 commonComp是 container 的路由前 向历史路由里添加新记录
  if (matchedRoute) {
    console.log(to)
    const newHistoryRoute = { name: to.meta.name, routeName: to.name, params: to.params }
    store.commit('AddRouteHistory', newHistoryRoute)

    // 并且改变侧边栏
    store.commit('SetMenuByRouteChange', newHistoryRoute)
  }

  // 向store commit 路由跳转成功事件
  store.commit('ToogleRouteComplete')
  next()
})

export { router }
